package com.fxw.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @ClassName MyBatisConfig
 * @Deacription TODO
 * @Author hqq
 * @Date 2021/10/25 22:04
 * @Version 1.0
 **/
@Configuration
@EnableTransactionManagement
public class MyBatisPlusConfig {

    //@Resource(name = "myRoutingDataSource")
    @Autowired
    private DataSource myRoutingDataSource;

    /*@Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(myRoutingDataSource);
        // 下面的不可少，这个有了，就不用配置文件里的
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }*/

      @Bean
      public SqlSessionFactory sessionFactory() throws Exception {
          MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
          sqlSessionFactoryBean.setDataSource(myRoutingDataSource);
          PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
          //下面的不可少，这个有了，就不用配置文件里的
          sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/*.xml"));
          return sqlSessionFactoryBean.getObject();
      }

      //Spring事务管理器
      @Bean
      public PlatformTransactionManager platformTransactionManager() {
          return new DataSourceTransactionManager(myRoutingDataSource);
      }
}
